﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FSM
{
    public struct sFsmTable
    {
        /// <summary>
        /// 事件
        /// </summary>
        public int Event;
        /// <summary>
        /// 现态
        /// </summary>
        public int CurState;
        /// <summary>
        /// 动作
        /// </summary>
        public Action<IntPtr> EventActFun;
        /// <summary>
        /// 次态
        /// </summary>
        public int NextState;

    }

    public struct sFSM
    {
        /// <summary>
        /// 状态迁移表
        /// </summary>
        public List<sFsmTable> FsmTable;
        /// <summary>
        /// 状态机当前状态
        /// </summary>
        public int curState;
        /// <summary>
        /// 状态机状态迁移数量
        /// </summary>
        public int stuMaxNum;
    }
    public class Fsm
    {
        /// <summary>
        /// 状态转换
        /// </summary>
        /// <param name="sFSM"></param>
        /// <param name="state"></param>
        public static void FSM_StateTransfer(ref sFSM sFSM, int state)
        {
            sFSM.curState = state;
        }

        /// <summary>
        /// 状态机处理方法
        /// </summary>
        /// <param name="sFSM">状态机对象</param>
        /// <param name="Event">触发事件</param>
        /// <param name="parm">动作执行参数</param>
        public static void FSM_EventHandle(ref sFSM sFSM, int Event, IntPtr parm)
        {
            List<sFsmTable> AcTable = sFSM.FsmTable;
            Action<IntPtr> EventActFun = null;
            int NextState = 0;
            int CurState = sFSM.curState;
            bool flag = false;

            for (int i = 0; i < sFSM.stuMaxNum; i++) //遍历状态表
            {
                if (Event == AcTable[i].Event && CurState == AcTable[i].CurState)
                {
                    flag = true;
                    EventActFun = AcTable[i].EventActFun;
                    NextState = AcTable[i].NextState;
                    break;
                }
            }
            if(flag)
            {
                if(EventActFun != null)
                {
                    EventActFun(parm);      //执行相应动作
                }
                FSM_StateTransfer(ref sFSM, NextState);     //状态转换
            }
            else
            {

            }
        }

        /// <summary>
        /// 状态机初始化
        /// </summary>
        /// <param name="sFSM">状态机对象</param>
        /// <param name="Table">状态迁移表</param>
        /// <param name="stuMaxNum">迁移表数量</param>
        /// <param name="curState">当前状态</param>
        public static void FSM_Init(ref sFSM sFSM, List<sFsmTable> Table, int stuMaxNum, int curState)
        {
            sFSM.FsmTable = Table;
            sFSM.curState = curState;
            sFSM.stuMaxNum = stuMaxNum;
        }
    }
}
